package com.bytearch.fast.cloud.algorithm.demo;

import com.bytearch.fast.cloud.algorithm.pojo.SeatInfoVO;

import java.util.*;

public class SeatCAS {
    /**
     * 原始flag值
     */
    private Long originSeatFlag = 0L;

    /**
     * 座位最大值
     */
    private Long seatFlagMax = 0L;

    /**
     * 座位数
     */
    private int seatNum = 0;


    private Map<String, Long> seatMap = new HashMap<>();

    /**
     * 初始化座位
     *
     * @return
     */
    public List<SeatInfoVO> initSeat(List<SeatInfoVO> seatInfoVOS) {
        //座位数
        this.seatNum = seatInfoVOS.size();
        //座位最大值
        this.seatFlagMax = (1L << this.seatNum) - 1;
        //给每一个座位分配编码
        int i = 0;
        for (SeatInfoVO seatInfoVO : seatInfoVOS) {
            if (seatInfoVO.getSeatFlag() != null) {
                throw new IllegalArgumentException("座位初始化失败");
            }
            //每次移动一位
            seatInfoVO.setSeatFlag(1L << i++);
            seatMap.put(seatInfoVO.getSeatNo(), seatInfoVO.getSeatFlag());
        }
        return seatInfoVOS;
    }

    /**
     * 获取占座编码flag
     *
     * @param seatNos
     * @return
     */
    public long haveSeatFlag(List<String> seatNos) {
        long haveSeatsFlag = 0L;
        for (String seatNo : seatNos) {
            //座位编码
            Long seatFlag = seatMap.get(seatNo);
            haveSeatsFlag |= seatFlag;
        }
        return haveSeatsFlag;
    }

    /**
     * 占有座位 --- 通过座位编号占有
     *
     * @return
     */
    public boolean canCasSeat(long seatFlag) {
        //座位是否已满
        if (isFull()) {
            return false;
        }

        if ((originSeatFlag & seatFlag) != 0) {
            //所需的位置有被占用的
            return false;
        }
        return true;
    }

    /**
     * 座位是否已满
     *
     * @return
     */
    public boolean isFull() {
        return  originSeatFlag.equals(this.seatFlagMax);
    }

    public static void main(String[] args) {
        List<SeatInfoVO> seatInfoVOS = new ArrayList<>();
        SeatInfoVO seatInfoVO = new SeatInfoVO();
        seatInfoVO.setSeatNo("01");
        seatInfoVO.setId(1);
        seatInfoVOS.add(seatInfoVO);

        SeatInfoVO seatInfoVO2 = new SeatInfoVO();
        seatInfoVO2.setSeatNo("02");
        seatInfoVO2.setId(2);
        seatInfoVOS.add(seatInfoVO2);

        SeatCAS seatCAS = new SeatCAS();
        seatCAS.initSeat(seatInfoVOS);
        System.out.println(seatCAS);

        long l = seatCAS.haveSeatFlag(Arrays.asList("01", "02"));
        System.out.println(l);
        boolean b = seatCAS.canCasSeat(l);
        System.out.println(b);


    }
}